﻿namespace D.Domain.SystemDomain.SysUserDomain.Entities
{
    /// <summary>
    /// 用户登录结果实体
    /// </summary>
    public class SysAdminLoginFailEntity : BaseEntity
    {
        /// <summary>
        /// 是否锁定
        /// </summary>
        private bool isLockOut;

        /// <summary>
        /// 用户
        /// </summary>
        public SysUserEntity SysAdminEntity { get; init; }

        /// <summary>
        /// 锁定结束时间
        /// </summary>
        public DateTime? LockEnd { get; private set; }

        /// <summary>
        /// 登录失败次数
        /// </summary>
        public int AccessFailCount { get; private set; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sysAdminEntity"></param>
        public SysAdminLoginFailEntity(SysUserEntity sysAdminEntity)
        {
            this.Id = Guid.NewGuid();
            this.SysAdminEntity = sysAdminEntity;
        }

        /// <summary>
        /// 重置
        /// </summary>
        public void Reset()
        {
            this.AccessFailCount = 0;
            this.LockEnd = null;
            this.isLockOut = false;
        }

        /// <summary>
        /// 处理登录失败5次记录
        /// </summary>
        public void Fail()
        {
            this.AccessFailCount++;
            if (this.AccessFailCount >= 5)
            {
                this.isLockOut = true;
                this.LockEnd = DateTime.Now.AddMinutes(5);
            }
        }

        /// <summary>
        /// 账户是否锁定
        /// </summary>
        /// <returns></returns>
        public bool IsLockOut()
        {
            if (this.isLockOut)
            {
                if (DateTime.Now > this.LockEnd)
                {// 已超过锁定时间
                    Reset();
                    return false;
                }
                return true;
            }
            return false;
        }
    }
}
